package org.tong.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

//@Configuration
public class DbSecurityConf extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    final String pwdQuery = "select user_name, pwd, available from t_user where user_name=?";
    final String roleQuery = "select u.user_name, r.role_name from t_user u, t_role_user ur, t_role r where u.id=ur.user_id and r.id = ur.role_id and u.user_name = ?";

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.jdbcAuthentication()
                .passwordEncoder(encoder)
                .dataSource(dataSource)
                .usersByUsernameQuery(pwdQuery)
                .authoritiesByUsernameQuery(roleQuery);

    }
}
